<?php
/**
 * Created by PhpStorm.
 * User: boye009
 * Date: 2016/3/17
 * Time: 9:20
 */

namespace Bbs\Api;

use Bbs\Model\ForumAdmingroupModel;
use Bbs\Model\ForumForumModel;
use Bbs\Model\ForumPostModel;
use Bbs\Model\ForumThreadModel;
use Common\Api\Api;

class ForumThreadApi extends Api{


    /**
     * 添加
     */
    const ADD = "Bbs/ForumThread/add";
    /**
     * 保存
     */
    const SAVE = "Bbs/ForumThread/save";
    const COUNT = "Bbs/ForumThread/count";
    /**
     * 保存根据ID主键
     */
    const SAVE_BY_ID = "Bbs/ForumThread/saveByID";

    /**
     * 删除
     */
    const DELETE = "Bbs/ForumThread/delete";

    /**
     * 多选删除
     */
    const DELETE_ALL = "Bbs/ForumThread/delete_all";

    /**
     * 查询
     */
    const QUERY = "Bbs/ForumThread/query";
    const QUERY_NO_PAGING = "Bbs/ForumThread/queryNoPaging";
    /**
     * 查询一条数据
     */
    const GET_INFO = "Bbs/ForumThread/getInfo";
    /**
     * 查询
     */
    const QUERY_WITH_COUNT = "Bbs/ForumThread/queryWithCount";
    const QUERY_WITH_COUNT2 = "Bbs/ForumThread/queryWithCount2";

    /**
     * 发表主题帖子
     */
    const ADD_THREAD = "Bbs/ForumThread/addThread";

    /**
     * 假删除
     */
    const PRETEND_DELETE = "Bbs/ForumThread/pretendDelete";

    /**
     * 假删除
     */
    const PRETEND_DELETE_BY_MAP = "Bbs/ForumThread/pretendDeleteByMap";

    const STICK = "Bbs/ForumThread/stick";


    const DIGEST = "Bbs/ForumThread/digest";

    /**
     * 增加
     */
    const SET_INC = "Bbs/ForumThread/setInc";

    /**
     * 减少
     */
    const SET_DEC ="Bbs/ForumThread/setDec";

    /**
     * 查询首页帖子
     */
    const QUERY_HEAD_THREADS ="Bbs/ForumThread/queryHeadThreads";


    protected function _init(){
        $this -> model = new ForumThreadModel();
    }

    public function delete_all($ids,$uid){
        //验证帖子
        foreach($ids as $tid){
            //获取主题帖信息
            $res2 = apiCall(ForumThreadApi::GET_INFO,array(array('tid'=>$tid)));
            if(!$res2['status']){
                return $this -> apiReturnErr($res2['info']);
            }
            if($res2['info']['status'] == -1){
                return $this -> apiReturnErr("该主题帖不存在");
            }

            //验证是否是自己的主题帖
            if($uid != $res2['info']['author_id']){
                //用户权限验证
                $res = apiCall(ForumUserAdmingroupApi::POWER,array($uid));
                if(!$res['status']){
                    return $this -> apiReturnErr($res['info']);
                }
                $power = $res['info'];
                if(is_array($power)){
                    //验证是否有删帖权限
                    if($power[ForumAdmingroupModel::ALLOW_DEL_POST] !=1 || ($power['fid'] != $res2['info']['fid'] && $power['fid'] != 0)){
                        return $this -> apiReturnErr("无权限");
                    }
                }else{
                    return $this -> apiReturnErr($power);
                }

            }
        }
        $map['tid'] = array('in',$ids);
        $result = apiCall(ForumThreadApi::PRETEND_DELETE_BY_MAP,array($map,$uid));
        if($result['status']){
            return $this -> apiReturnSuc($result['info']);
        }else{
            return $this -> apiReturnErr($result['info']);
        }
    }

    public function delete($tid,$uid){
        //获取主题帖信息
        $res2 = apiCall(ForumThreadApi::GET_INFO,array(array('tid'=>$tid)));
        if(!$res2['status']){
            return $this -> apiReturnErr($res2['info']);
        }
        if($res2['info']['status'] == -1){
            return $this -> apiReturnErr("该主题帖不存在");
        }

        //验证是否是自己的主题帖
        if($uid != $res2['info']['author_id']){
            //用户权限验证
            $res = apiCall(ForumUserAdmingroupApi::POWER,array($uid));
            if(!$res['status']){
                return $this -> apiReturnErr($res['info']);
            }
            $power = $res['info'];
            if(is_array($power)){
                //验证是否有删帖权限
                if($power[ForumAdmingroupModel::ALLOW_DEL_POST] !=1 || ($power['fid'] != $res2['info']['fid'] && $power['fid'] != 0)){
                    return $this -> apiReturnErr("无权限");
                }
            }else{
                return $this -> apiReturnErr($power);
            }

        }

        $result = apiCall(ForumThreadApi::PRETEND_DELETE,array($tid));

        if($result['status']){
            return $this -> apiReturnSuc($result['info']);
        }else{
            return $this -> apiReturnErr($result['info']);
        }
    }

    public function digest($uid,$tid,$digest_value){

        $map = array(
            'tid' => $tid,
        );
        $result = apiCall(ForumThreadApi::GET_INFO,array($map));
        if($result['status']){
            if(is_null($result['info'])){
                return $this -> apiReturnErr('主题帖id参数错误');
            }
        }else{
            return $this -> apiReturnErr($result['info']);
        }

        //用户验证
        $res = apiCall(ForumUserAdmingroupApi::POWER,array($uid));
        if($res['status']){
            $power = $res['info'];
            if(is_array($power)){
                if($power[ForumAdmingroupModel::ALLOW_DIGEST_THREAD] != 1 || ($power['fid'] != $result['info']['fid'] && $power['fid'] != 0) ){
                    return $this -> apiReturnErr("无权限");
                }
            }else{
                return $this -> apiReturnErr($power);
            }
        }else{
            return $this -> apiReturnErr($res['info']);
        }

        $entity = array(
            'digest' => $digest_value,
        );
        if($digest_value == 0){
            //取消精华
            if($result['info']['digest'] == 0){
                return $this -> apiReturnErr('该帖子非精华');
            }
            $result = apiCall(ForumThreadApi::SAVE,array($map,$entity));
            if($result['status']){
                return $this -> apiReturnSuc('取消精华成功');
            }else{
                return $this -> apiReturnErr($result['info']);
            }
        }else if($digest_value == 1){
            //加精
            if($result['info']['digest'] == 1){
                return $this -> apiReturnErr('该贴子已经是精华帖');
            }
            $result = apiCall(ForumThreadApi::SAVE,array($map,$entity));
            if($result['status']){
                return $this -> apiReturnSuc('加精成功');
            }else{
                return $this -> apiReturnErr($result['info']);
            }
        }

    }

    public function stick($uid,$tid,$stick_value){

        $map = array(
            'tid' => $tid,
        );
        $result = apiCall(ForumThreadApi::GET_INFO,array($map));
        if($result['status']){
            if(is_null($result['info'])){
                return $this -> apiReturnErr('主题帖id参数错误');
            }
        }else{
            return $this -> apiReturnErr($result['info']);
        }

        //用户验证
        $res = apiCall(ForumUserAdmingroupApi::POWER,array($uid));
        if($res['status']){
            $power = $res['info'];
            if(is_array($power)){
                if($power[ForumAdmingroupModel::ALLOW_STICK_THREAD] != 1 || ($power['fid'] != $result['info']['fid'] && $power['fid'] != 0) ){
                    return $this -> apiReturnErr("无权限");
                }
            }else{
                return $this -> apiReturnErr($power);
            }
        }else{
            return $this -> apiReturnErr($res['info']);
        }

        $entity = array(
            'stick' => $stick_value,
        );
        if($stick_value == 0){
            if($result['info']['stick'] == 0){
                return $this -> apiReturnErr('该帖非置顶帖');
            }
            $result = apiCall(ForumThreadApi::SAVE,array($map,$entity));
            if($result['status']){
                return $this -> apiReturnSuc('取消置顶成功');
            }else{
                return $this -> apiReturnErr($result['info']);
            }
        }else if($stick_value == 1){
            if($result['info']['stick'] == 1){
                return $this -> apiReturnErr('该帖已经置顶');
            }
            $result = apiCall(ForumThreadApi::SAVE,array($map,$entity));
            if($result['status']){
                return $this -> apiReturnSuc('置顶成功');
            }else{
                return $this -> apiReturnErr($result['info']);
            }
        }

    }

    public function pretendDelete($tid,$fid){
        //假删除主题帖
        $map = array(
            'tid' => $tid,
        );
        $data = array(
            'status' => -1,//删除状态
        );
        $this -> model -> startTrans();//启动事务
        $forumModel = new ForumForumModel();
        $result = $this -> model -> where($map) -> save($data);
        if($result === false){
            $error = $this -> model -> getDbError();
            return $this -> apiReturnErr($error);
        }else{

            $map = array(
                'fid' => $fid,
            );
            $result = $forumModel -> where($map) -> setDec('threads');
            if($result === false){
                $error = $forumModel -> getError();
                $this -> model -> rollback();
                return $this -> apiReturnErr($error);
            }else{
                $this -> model -> commit();
                return $this -> apiReturnSuc("删除成功!");
            }
        }

    }

    public function pretendDeleteByMap($map,$fid){
        //假删除主题帖
        $data = array(
            'status' => -1,//删除状态
        );
        $this -> model -> startTrans();//启动事务
        $forumModel = new ForumForumModel();
        $result = $this -> model -> where($map) -> save($data);
        if($result === false){
            $error = $this -> model -> getDbError();
            return $this -> apiReturnErr($error);
        }else{
            $num = count($map['tid']['in']);
            $map = array(
                'fid' => $fid,
            );
            $result = $forumModel -> where($map) -> setDec('threads',$num);
            if($result === false){
                $error = $forumModel -> getError();
                $this -> model -> rollback();
                return $this -> apiReturnErr($error);
            }else{
                $this -> model -> commit();
                return $this -> apiReturnSuc("删除成功!");
            }
        }

    }

    public function queryWithCount2($map = null, $page = array('curpage'=>0,'size'=>10), $order = false, $params = false, $fields = false){

        $query = $this->model;
        if(!is_null($map)){
            $query = $query->where($map);
        }
        if(!($order === false)){
            $query = $query->order($order);
        }
        if(!($fields === false)){
            $query = $query->field($fields);
        }
        $list = $query -> page($page['curpage'] . ',' . $page['size']) -> select();

        if ($list === false) {
            $error = $this -> model -> getDbError();
            return $this -> apiReturnErr($error);
        }
        $count = $this -> model ->field('tid')-> where($map)-> count();

        // 查询满足要求的总记录数
        $Page = new \Think\Page($count, $page['size']);

        //分页跳转的时候保证查询条件
        if ($params !== false) {
            foreach ($params as $key => $val) {
                $Page -> parameter[$key] = urlencode($val);
            }
        }
        // 实例化分页类 传入总记录数和每页显示的记录数
        $show = $Page -> show();
        return $this -> apiReturnSuc(array("count" => $count, 'show' => $show, "list" => $list));

    }

    public function queryWithCount($map = null, $map_invisible = null, $page = array('curpage'=>0,'size'=>10), $order = false, $params = false, $fields = false){

        $query = $this->model -> join("(select tid,invisible from itboye_forum_post where position=0) as post on itboye_forum_thread.tid=post.tid") -> join("itboye_forum_forum on itboye_forum_thread.fid=itboye_forum_forum.fid","left");
        if(!is_null($map)){
            $query = $query->where($map);
        }
        if(!is_null($map_invisible)){
            $query = $query -> where($map_invisible);
        }
        if(!($order === false)){
            $query = $query->order($order);
        }
        if(!($fields === false)){
            $query = $query->field($fields);
        }
        $list = $query -> page($page['curpage'] . ',' . $page['size']) -> select();

        if ($list === false) {
            $error = $this -> model -> getDbError();
            return $this -> apiReturnErr($error);
        }

        if(!is_null($map_invisible)){
            $count = $this -> model -> where($map) -> where($map_invisible) -> join("(select tid,invisible from itboye_forum_post where position=0) as post on itboye_forum_thread.tid=post.tid") -> join("itboye_forum_forum on itboye_forum_thread.fid=itboye_forum_forum.fid","left") -> count();
        }else{
            $count = $this -> model -> where($map) -> join("(select tid,invisible from itboye_forum_post where position=0) as post on itboye_forum_thread.tid=post.tid") -> join("itboye_forum_forum on itboye_forum_thread.fid=itboye_forum_forum.fid","left") -> count();
        }

        // 查询满足要求的总记录数
        $Page = new \Think\Page($count, $page['size']);

        //分页跳转的时候保证查询条件
        if ($params !== false) {
            foreach ($params as $key => $val) {
                $Page -> parameter[$key] = urlencode($val);
            }
        }

        // 实例化分页类 传入总记录数和每页显示的记录数
        $show = $Page -> show();

        return $this -> apiReturnSuc(array("count" => $count, 'show' => $show, "list" => $list));

    }

    //废弃
    public function addThread($thread_entity,$post_entity){

        $tid = 0;

        $this -> model -> startTrans();//开启事务

        $result = $this -> model -> create($thread_entity,1);

        $error = false;
        if($result === false){
            $error = $this -> model -> getDbError();
        }else{
            $result = $this -> model -> add();
            if($result === false){
                $error = $this -> model -> getDbError();
            }else{
                $tid = $result;
            }
        }

        if($error === false){
            //未出错
            $forumPost = new ForumPostModel();
            $post_entity['tid'] = $tid;
            $result = $forumPost -> create($post_entity,1);

            if($result === false){
                $error = $this -> model -> getDbError();
                $this -> model -> rollback();
            }else{
                $result = $forumPost -> add();
                if($result === false){
                    $error = $this -> model -> getDbError();
                    $this -> model -> rollback();
                }else{
                    $pid = $result;
                    $this -> model -> commit();
                    $allId = array(
                        'tid' => $tid,
                        'pid' => $pid,
                    );
                    return $this -> apiReturnSuc($allId);
                }
            }
        }

        return $this -> apiReturnErr($error);

    }

    /**
     * 查询首页帖子（首页+最新）
     * @param $maxhead 最大首页显示帖子数量
     * @param $maxnew  最大最新帖子数量
     * @param $max 最大数量
     */
    public function queryHeadThreads($max=4,$img_num=3){
        //首先查询首页显示帖子,按照论坛顺序
        $model = $this->model;
        $limit = $max;
        $field = 't.dateline,t.author,t.author_id,replies,likes,t.subject,t.fid,t.tid,views,message';

        $result = $model->alias('t')->join('__FORUM_FORUM__ as f on t.fid = f.fid','RIGHT')
            ->join('__FORUM_POST__ as p on t.tid = p.tid','LEFT')
            ->where('t.position=1 and (invisible=1 or modnewposts=0) and p.position=0')
            ->order('displayorder desc')
            ->field($field)
            ->limit($limit)
            ->select();

        if($result===false){
            $error = $this->model->getDbError();
            return $this->apiReturnErr($error);
        }else{
            $threads = $result;
            $num = count($threads);
            if($num < $max){
                //帖子数量小于目标数量,算上最新帖子
                $limit = $max - $num;
                $result = $model->alias('t')->join('__FORUM_FORUM__ as f on t.fid = f.fid','RIGHT')
                    ->where('t.position!=1 and (invisible=1 or modnewposts=0) and p.position=0')
                    ->limit($limit)
                    ->field($field)
                    ->order('update_time desc')
                    ->select();

                if($result===false){
                    $error = $this->model->getDbError();
                    return $this->apiReturnErr($error);
                }
                $threads = array_merge($threads,$result);

            }
            //查询附件、作者信息
            foreach($threads as &$val){
                //获取发表时间展示信息
                $time = time() - $val['dateline'];
                $val['dateline_show'] = $this->getDateInfo($time,$val['dateline']);
                
                //查询用户信息
                $result = apiCall('Api/BbsUserCenter/userInfo',array($val['author_id']),'Domain');
                if($result['status']){
                    $val['user_info'] = $result['info'];
                }

                //获取图片信息
                $map = array(
                    'tid' => $val['tid'],
                );
                $field = "aid,pid";
                $res = apiCall(ForumAttachmentApi::QUERY_NO_PAGING,array($map,false,$field));
                if($res['status']){
                    $val['img'] = array();
                    $i = 0;
                    foreach($res['info'] as $v){
                        //判断附件所属帖子是否能显示（审核通过与否）
                        $post_info = apiCall(ForumPostApi::GET_INFO,array(array('pid'=>$v['pid'])));
                        if($post_info['status']){
                            if(is_null($post_info['info'])){
                                continue;
                            }elseif($post_info['info']['status']==0 || ($post_info['info']['invisible']==0 && $modnewposts==1)){
                                //删除的帖子和未通过审核的附件不显示
                                continue;
                            }
                        }else{
                            continue;
                        }

                        array_push($val['img'],$v['aid']);
                        $i++;
                        if($i == $img_num){
                            break;
                        }
                    }
                }else{
                    $this -> apiReturnErr($res['info']);
                }

            }

            return $this->apiReturnSuc($threads);

        }
        
    }
    private  function getDateInfo($time,$dateline){

        if($time <= 60){
            return "刚刚";
        }else if($time > 60 && $time <= 3600){
            return floor($time/60)."分钟前";
        }else if($time > 3600 && $time <= 3600*24){
            return floor($time/3600)."小时前";
        }else if($time > 3600*24){
            return date('Y-m-d',$dateline);
        }

    }


}